package godget.client;


import java.util.Vector;

import godget.client.GoGame.EFieldState;
import godget.client.GoGame.FieldChange;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlexTable;

/***
 * Widget to display go game and manage user interaction
 * @author reimer
 */
public class GoWidget extends FlexTable {
	
	protected int size;
	protected boolean status;
	protected GoGame goGame;
	
	public GoWidget( int size )
	{
		super();
		this.getElement().setId("gogadget");
		this.size = size;
		this.status = true;			// black starts

		
		for ( int i=0; i<this.size; i++ )
		{
			for ( int j=0; j<this.size; j++)
				this.setHTML(i, j, "<img src=\"./empty.jpg\">");
		}
		
		this.goGame = new GoGame( size );
		
		this.addClickHandler( new GoClickHandler());
	}
	
	public GoWidget()
	{
		this(9);
	}

	/**
	 * @param size the size to set
	 */
	public void setSize(int size) {
		this.size = size;
	}

	/**
	 * @return the size
	 */
	public int getSize() {
		return size;
	}
	
	protected String FieldStateToHTML( EFieldState state)
	{
		switch( state )
		{
		case EMPTY:
			return "<img src=\"empty.jpg\">";
		case BLACK:
			return "<img src=\"black.jpg\">";
		case WHITE:
			return "<img src=\"white.jpg\">";
		}
		return "";
	}
	
	
	class GoClickHandler implements ClickHandler
	{

		/**
		comment to Reimer: this had an override tag.
		However, it is a method implementing an interface,
		not a method overriding a superclass method.
		I removed the wrong tag so the code compiles again.
		
		Konrad.
		*/ 
		public void onClick(ClickEvent event) {
			Cell cell = getCellForEvent(event);
			if ( cell == null )
				return;
			
			FieldChange turn = new FieldChange(cell.getRowIndex(), cell.getCellIndex(),
					( status ? EFieldState.BLACK : EFieldState.WHITE) );
			
			Vector<FieldChange> result = goGame.SetStone(turn);
			
			if( ! result.isEmpty() )
			{
				status = !status;
				for ( int i = 0; i < result.size(); i++)
					setHTML(result.elementAt(i).row, result.elementAt(i).column, 
							FieldStateToHTML(result.elementAt(i).state ));
			}
		}
	
	}

}
